package com.mw.job.ui.controller;

import com.github.jsonzou.jmockdata.JMockData;
import com.github.jsonzou.jmockdata.utils.TypeReference;
import com.mw.job.ui.bean.ClusterInfo;
import com.mw.job.ui.bean.Node;
import com.mw.job.ui.bean.ZkProperties;
import com.mw.job.ui.util.HelpMe;
import com.mw.job.ui.zookeeper.CuratorClient;
import com.xiaoleilu.hutool.http.HttpUtil;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
public class IndexController {

	private Logger log = LoggerFactory.getLogger(getClass());

	private static final String root = "/MW-JOB";

	@Autowired
	ZkProperties zkProperties;

	@Autowired
	ServerProperties serverProperties;

	private static ZooKeeper zooKeeper = null;


	@RequestMapping("/")
	public String index(HttpServletRequest request, Model model){

		log.info("index 首页");

		if (zooKeeper==null){
			zooKeeper = CuratorClient.zooKeeper();
		}

		log.info(zooKeeper.toString());

		List<ClusterInfo> list = null;

		boolean flag = false;

		if (flag){//模拟数据返回
			list = JMockData.mockCollection(new TypeReference<List<ClusterInfo>>(){});
		}else {
			List<String> clusterNodeList = getChildrenFromZk(root);
			if (HelpMe.isNotNull(clusterNodeList)){
				List<ClusterInfo> clusterInfoList = new ArrayList<>();
				for (String clusterNode:clusterNodeList){
					String tempPath = root + "/" + clusterNode;
					String clusterNodeVal = getDataFromZk(tempPath);
					ClusterInfo clusterInfo = new ClusterInfo(clusterNode,clusterNodeVal);

					String tempPath2 = tempPath + "/" + "node";
					List<String> nodeList = getChildrenFromZk(tempPath + "/" + "node");
					if (HelpMe.isNotNull(nodeList)){
						List<Node> nodes = new ArrayList<>();
						for (String node:nodeList){
							String nodeVal = getDataFromZk(tempPath2+"/"+node);
							nodes.add(getNode(node,nodeVal));
						}
						clusterInfo.setNodeList(nodes);
					}
					clusterInfoList.add(clusterInfo);
				}
				list = clusterInfoList;
			}
		}


		model.addAttribute("list",list);

		return "index";
	}



	@RequestMapping("/trigger")
	@ResponseBody
	public String trigger(String url){


		String temp = url + "/trigger";

		String flag = HttpUtil.get(temp);

		log.info("trigger 节点状态，url --> "+temp);

		return flag;
	}



	private List<String> getChildrenFromZk(String path){
		try {
			List<String> children = zooKeeper.getChildren(path, false);
			return children;
		} catch (KeeperException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return null;
	}


	private String getDataFromZk(String path){
		try {
			byte[] data = zooKeeper.getData(path, false, null);
			String val = "";
			if (data!=null){
				val = new String(data, Charset.forName("UTF-8"));
			}
			return val;
		} catch (KeeperException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return "";
	}


	private Node getNode(String node,String nodeVal){

		String[] nodeArr = node.split(":");

		StringBuffer sb = new StringBuffer();
		sb.append("http://");
		sb.append(nodeArr[0]);
		sb.append(":");
		sb.append(nodeArr[1]);
		sb.append("/");
		sb.append(nodeArr[2]);

		String nodeUrl = sb.toString();

		sb.append("/state");
		String url = sb.toString();


		Node result = null;

		Map<String, String> map = HelpMe.easyStr2Map(nodeVal, ",", "=");

		try {
			result = HelpMe.map2BeanAgain(Node.class,map,null);
			result.setNodeInfo(nodeUrl);

			String loopTime = "";
			if (result.getCornTask()){
				loopTime = result.getLoopTime()+" (corn表达式)";
			}else {
				loopTime = result.getLoopTime()+" (ms)";
			}
			result.setLoopTime(loopTime);

			String state = HttpUtil.get(url);

			boolean flag = Boolean.parseBoolean(state);
			result.setProducerState(!flag);

			log.info("节点状态url --> "+url);
			if (flag){
				log.info("节点生产者状态 --> 关闭！");
			}else {
				log.info("节点生产者状态 --> 开启！");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}




}



















